package com.xxjh.brs.map.utils;

import com.xxjh.brs.map.vo.DownloadProgress;

import static com.xxjh.brs.map.utils.MapDownLoadConstants.IMG_SIZE;

/**
 * @author CHENCHEN
 * @title 下载进程
 * @company 新兴际华科技（天津）有限公司
 * @create 2024-07-03 19:21
 */
public class ProgressCalculation {

    public static void updateDownloadSpeed(DownloadProgress progress) {
        long currentTime = System.currentTimeMillis();
        if(progress != null){
            long elapsedTime = currentTime - progress.getLastUpdateTime();
            if (elapsedTime > 0) {
                long bytesDownloadedSinceLastUpdate = (progress.getDownloadedTiles() - progress.getLastDownloadedTiles()) * IMG_SIZE;
                double speedBps = bytesDownloadedSinceLastUpdate * 1000.0 / elapsedTime;
                String formattedSpeed = formatSpeed(speedBps);
                progress.setCurrentSpeed(formattedSpeed);
                progress.updateTimeAndDownloadedTiles(); // 更新时间戳和已下载瓦片数
            }
            progress.setStatus(progress.getDownloadedTiles() == progress.getTotalTiles() ? "completed" : "loading");
            progress.setPercentage(String.format("%.2f%%", (double) progress.getDownloadedTiles() / progress.getTotalTiles() * 100));
        }
    }

    private static String formatSpeed(double speedBps) {
        if (speedBps >= 1024 * 1024) {
            return String.format("%.2f MB/s", speedBps / (1024 * 1024));
        } else if (speedBps >= 1024) {
            return String.format("%.2f KB/s", speedBps / 1024);
        } else {
            return String.format("%.2f B/s", speedBps);
        }
    }
}
